package com.lhl.blog.common.utils;

import com.lhl.blog.common.exception.BlogException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Slf4j
public class SecurityUtil {
    /**
     * 加密
     */
    public static String encrypt(String password){
        //校验密码不能为空
        if (!StringUtils.hasLength(password)){
            throw new BlogException("密码不能为空！");
        }

        //生成盐值
        String salt = UUID.randomUUID().toString().replace("-","");
        //进行加密
        String securityPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes(StandardCharsets.UTF_8));
        //将盐值和密文存储到数据库中
        return salt+securityPassword;
    }

    /**
     * 验证
     */
    public static Boolean verify(String inputPassword,String sqlPassword){
        //对参数进行校验
        if (!StringUtils.hasLength(inputPassword) || !StringUtils.hasLength(sqlPassword)){
            return false;
        }
        if (sqlPassword.length() != 64){
            return false;
        }
        //获取盐值
        String salt = sqlPassword.substring(0,32);

        //进行验证
        String securityPassword = DigestUtils.md5DigestAsHex((salt + inputPassword).getBytes(StandardCharsets.UTF_8));

        return sqlPassword.equals(salt + securityPassword);

    }


}









